using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MTRC.ODMS.DAL;
using MTRC.ODMS.DAL.SOM.CodeSetup;
using AjaxControlToolkit;
using System.Text;
using System.Security.Cryptography;
using System.IO;




namespace MTRC.ODMS.Web.SOM.AdmissionRegistry
{


    /// <summary>
    /// author:HeZhixiang
    /// </summary>
    public partial class AdmissionRegistryEnquiry : BasePage_SOM
    {
        #region Property

        /// <summary>
        /// MenuID
        /// </summary>
        protected override string MenuID
        {
            get
            {
                return "M140101";
            }
        }

        protected int DetailLength
        {
            get
            {
                if (ViewState["DetailLength"] != null)
                {
                    return int.Parse(ViewState["DetailLength"].ToString());
                }
                else
                {
                    return 20;
                }
            }
            set
            {
                ViewState["DetailLength"] = value;
            }
        }

        #endregion

        #region Page Init And Load

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(ChangeLanguage_Function);
            this.grdSearchResult.NeedDataBind += new APJ.Web.UI.WebControls.CommonGridView.NeedDataBindHandler(grdSearchResult_NeedDataBind);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // add by dylan 20151030 for u275.1 
                this.grdSearchResult.PageSize = this.GridViewPageDefaultSize();

                //set control text about multi-language of page
                SetLanguage();
                //Custom element initial state of page 
                CustomInitializtion();
                if (Request.QueryString["isBack"] != null && Request.QueryString["isBack"].Trim() != string.Empty && Convert.ToInt32(Request.QueryString["isBack"].ToString()) > 0)
                {

                }
                else
                {
                    btnSearch_Click(null, EventArgs.Empty);
                }
                //btnSearch_Click(null, EventArgs.Empty);

                //added by Nathan 2015-08-15
                if (chkFreeTextSearch.Checked)
                {
                    TxtConditionOne.Enabled = true;
                    TxtConditionTwo.Enabled = true;
                    TxtConditionThree.Enabled = true;
                    rdoAnd.Enabled = true;
                    rdoOr.Enabled = true;

                }
                else
                {
                    TxtConditionOne.Enabled = false;
                    TxtConditionTwo.Enabled = false;
                    TxtConditionThree.Enabled = false;
                    rdoAnd.Enabled = false;
                    rdoOr.Enabled = false;
                    rdoAnd.Checked = true;
                    TxtConditionOne.Text = "";
                    TxtConditionTwo.Text = "";
                    TxtConditionThree.Text = "";
                    TextOne.Text = "";
                    TextTwo.Text = "";
                    TextThree.Text = "";
                }
                /*******************add by jack 20151202 for using session store enquiry condition start**********************/
                string isBack = Request.QueryString["isBack"];
                if (isBack == "1")
                {
                    this.ddlStation.SelectedValue = Session["Common_Station"].ToString();
                    this.dtbCreateTimeFrom.Text = Session["Common_DateFrom"].ToString();
                    this.dtbCreateTimeTo.Text = Session["Common_DateTo"].ToString();
                    //this.ddlWorkCategory.SelectedValue = Session["AR_WorkCategory"].ToString();
                    //this.ddlSubCategory.SelectedValue = Session["AR_SubCategory"].ToString();
                    if (Session["AR_WorkCategory"] != null && Session["AR_WorkCategory"].ToString() != "")
                    {
                        this.FindByValueAndSelect(ddlWorkCategory, Session["AR_WorkCategory"].ToString());
                        this.ddlWorkCategory_SelectedIndexChanged(null, null);
                    }
                    if (Session["AR_SubCategory"] != null && Session["AR_SubCategory"].ToString() != "")
                    {
                        this.FindByValueAndSelect(ddlSubCategory, Session["AR_SubCategory"].ToString());
                    }
                    this.SetCheckboxListValue(Session["Common_ShowList"].ToString(), this.cblShow);
                    Boolean boolFreeTextSearch = Convert.ToBoolean(Session["Common_FreeTextSearch"]);
                    this.chkFreeTextSearch.Checked = boolFreeTextSearch;
                    if (boolFreeTextSearch)
                    {
                        this.rdoAnd.Enabled = true;
                        this.rdoOr.Enabled = true;
                        this.TxtConditionOne.Enabled = true;
                        this.TxtConditionTwo.Enabled = true;
                        this.TxtConditionThree.Enabled = true;
                        this.TextOne.Text = Session["Common_ConditionOne"].ToString();
                        this.TextTwo.Text = Session["Common_ConditionTwo"].ToString();
                        this.TextThree.Text = Session["Common_ConditionThree"].ToString();
                    }
                    else
                    {
                        this.TxtConditionOne.ReadOnly = false;
                        this.TxtConditionTwo.ReadOnly = false;
                        this.TxtConditionThree.ReadOnly = false;
                    }
                    this.rdoAnd.Checked = Convert.ToBoolean(Session["Common_RdoAnd"]);
                    this.rdoOr.Checked = Convert.ToBoolean(Session["Common_RdoOr"]);
                }
                /*******************add by jack 20151202 for using session store enquiry condition end**********************/
            }
        }

        #endregion

        #region Event

        void ChangeLanguage_Function(object sender, EventArgs e)
        {
            //set control text about multi-language of page

            SetLanguage();
            if (IsPostBack) //added by huangyao 20090120
            {
                CustomInitializtion();
            }
            //bind the seach result
            BindSearchResult();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                //added by Nathan 2015-08-15
                if (chkFreeTextSearch.Checked)
                {
                    TxtJM();
                }

                BindSearchResult();
                if (grdSearchResult.Rows.Count != 0)
                {
                    btnOutPut.Enabled = true;
                }
                else
                {
                    btnOutPut.Enabled = false;
                }
            }
            finally
            {
                //add by gordon 20150812 | For Search Wait Cursor
                ToolkitScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", "showWait('');", true);
            }
        }

        protected void BFSearc_Click(object sender, EventArgs e)
        {
            try
            {
                //added by Nathan 2015-08-15
                if (chkFreeTextSearch.Checked)
                {
                    JMText();
                }

                BindSearchResult();
                if (grdSearchResult.Rows.Count != 0)
                {
                    btnOutPut.Enabled = true;
                }
                else
                {
                    btnOutPut.Enabled = false;
                }
            }
            finally
            {
                //add by gordon 20150812 | For Search Wait Cursor
                ToolkitScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", "showWait('');", true);
            }
        }

        /// <summary>
        /// sorting ,then afresh databind
        /// </summary>
        private void grdSearchResult_NeedDataBind()
        {
            BindSearchResult();
        }

        protected void ddlWorkCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlWorkCategory.SelectedIndex == 0)
            {
                BindWorkSubCategory();
            }
            else
            {
                string strWorkCategory = ddlWorkCategory.SelectedValue;
                DataView dvWorkSubCategory = new DataView();
                dvWorkSubCategory.Table = ODMS.DAL.SOM.CodeSetup.CDAdmRegSubCategory.GetAllWorkSubCategory(this.LangCode);
                dvWorkSubCategory.RowFilter = "AdmRegCategoryID = " + strWorkCategory;
                BindListControl(this.ddlSubCategory, "AdmRegSubCategoryID", "Description", dvWorkSubCategory.ToTable(), true);
                //HttpCookie cookie = Request.Cookies["AdmissionRegistryEnquiry_SubCategory2"];
                //if (cookie != null && !string.IsNullOrEmpty(cookie["IP"]))
                //{
                //    ddlSubCategory.SelectedValue = cookie["IP"];
                //    //cookie["IP"] = "";
                //}              
                if (TextGenSubCategory.Text.Trim().Length > 0)
                {
                    string subStr = TextGenSubCategory.Text;
                    ddlSubCategory.SelectedItem.Text = subStr;
                    TextGenSubCategory.Text = "";
                }

            }
        }

        protected void btnOutPut_Click(object sender, EventArgs e)
        {
            //edit by hjh 20120516 for issue 1531
            //if (this.hdnCacheDataReturnInt.Value != "0")
            //{
            //    DataSet dsReturn = BLL.SOM.TempData.GetCacheData(int.Parse(this.hdnCacheDataReturnInt.Value));
            if (dtbCreateTimeFrom.Text.Trim().Length > 0 && dtbCreateTimeTo.Text.Trim().Length > 0)
            {
                if (InvalidateInputDate(this.dtbCreateTimeFrom.GetDateTime(), this.dtbCreateTimeTo.GetDateTime()))
                {
                    Alert(this.GetMessage("COM_StartEndDate"));
                    return;
                }
            }
            DataSet dsReturn = GetSearchResult();
            object limitExpCount = DAL.CommonData.GetNumVal("SOM_AdmissionExportMAXControl");
            if (dsReturn == null)
            {
                /********edit by jack 20151130 for u253 Processing application errors and exceptions start****/
                // return;
                string errorMessage = string.Format(GetMessage("SOM_AdmissionRegistryEnquiryException", this.LangCode), GetLineNum());
                Application_Error(errorMessage, "AdmissionRegistryEnquiry.aspx.cs");
                /********edit by jack 20151130 for u253 Processing application errors and exceptions end****/
            }
            else if (limitExpCount != null && dsReturn.Tables[0].Rows.Count > int.Parse(limitExpCount.ToString()))//edit by hjh 20120516 for issue 1531
            {
                Alert(string.Format(this.GetMessage("SOM_ExportLimitControl"), int.Parse(limitExpCount.ToString())));
                return;
            }

            DataSet dsCopyReturn = new DataSet();
            dsCopyReturn = dsReturn.Copy();
            dsReturn.Dispose();
            dsReturn = null;
            DataTable dtSearchResult = new DataTable();
            dtSearchResult = dsCopyReturn.Tables[0];

            dtSearchResult.Columns.Remove("Remark1");
            dtSearchResult.Columns.Remove("HandoverNote");
            dtSearchResult.Columns.Remove("JobNature");
            dtSearchResult.Columns.Remove("JobLocation");
            dtSearchResult.Columns.Remove("JobProtection");
            dtSearchResult.Columns.Remove("StationEventID");
            dtSearchResult.Columns.Remove("EventStatusID");
            dtSearchResult.Columns.Remove("HandoverNote1");
            /******************* modifidy by dylan 20150727 for u133 start**********************************/
            dtSearchResult.Columns["EventNo"].ColumnName = this.GetLabel("SOM_EventNo");
            dtSearchResult.Columns["EventTime"].ColumnName = this.GetLabel("SOM_ArrivalTime");
            dtSearchResult.Columns["EventCompleteTime"].ColumnName = this.GetLabel("SOM_OffTime");
            dtSearchResult.Columns["StaffName"].ColumnName = this.GetLabel("COM_StaffName");
            dtSearchResult.Columns["DepartmentCompany"].ColumnName = this.GetLabel("SOM_DepartmentCompany");
            dtSearchResult.Columns["WorkCategory"].ColumnName = this.GetLabel("SOM_WorkCategory");
            dtSearchResult.Columns["WorkSubCategory"].ColumnName = this.GetLabel("SOM_WorkSubCategory");
            dtSearchResult.Columns["JobNature1"].ColumnName = this.GetLabel("SOM_Nature");
            dtSearchResult.Columns["JobLocation1"].ColumnName = this.GetLabel("SOM_Location");
            /******************* add by dylan 20150727 for u133 start**********************************/
            dtSearchResult.Columns["Remark"].ColumnName = this.GetLabel("COM_Remark");
            /******************* add by dylan 20150727 for u133 end**********************************/

            dtSearchResult.Columns["EventStatusDesc"].ColumnName = this.GetLabel("COM_Status");
            dtSearchResult.Columns["FlagHandover"].ColumnName = this.GetLabel("SOM_Handover");
            dtSearchResult.Columns.Add();
            for (int i = 0; i < dtSearchResult.Rows.Count; i++)
            {
                //if (dtSearchResult.Rows[i][11].ToString() == "1")
                if (dtSearchResult.Rows[i][12].ToString() == "1")
                {
                    //dtSearchResult.Rows[i][12] = GetLabel("SOM_HighLightYellow");
                    dtSearchResult.Rows[i][13] = GetLabel("SOM_HighLightYellow");
                }
                // else if (dtSearchResult.Rows[i][11].ToString() == "2")
                else if (dtSearchResult.Rows[i][12].ToString() == "2")
                {
                    //dtSearchResult.Rows[i][12] = GetLabel("SOM_HighLightRed");
                    dtSearchResult.Rows[i][13] = GetLabel("SOM_HighLightRed");
                }
                else
                {
                    //dtSearchResult.Rows[i][12] = GetLabel("SOM_HighLightNormal");
                    dtSearchResult.Rows[i][13] = GetLabel("SOM_HighLightNormal");
                }

            }
            /******************* modifidy by dylan 20150727 for u133 end**********************************/
            dtSearchResult.Columns.Remove("HighLight");
            //dtSearchResult.Columns[11].ColumnName = this.GetLabel("SOM_HighLight");
            dtSearchResult.Columns[12].ColumnName = this.GetLabel("SOM_HighLight");
            /******************* add by dylan 20150727 for u133 start**********************************/
            dtSearchResult.Columns[this.GetLabel("COM_Remark")].SetOrdinal(12);
            /******************* add by dylan 20150727 for u133 end**********************************/

            /******************* add by dylan 20150727 for u133 start**********************************/
            //Common.ExportExcel_showHHMM(dsCopyReturn, Context, "AdmissionRegistryEnquiry.xls");
            //CreateExcelFile.CreateExcelDocumentAsStream(dsCopyReturn, "AdmissionRegistryEnquiry.xls", Context.Response);
            //string templateFile = Server.MapPath("~") + string.Format(@"\Template\MTRC\AdmissionRegistryEnquiry Template.xlsx");
            string templateFilePath = APJ.Util.Utility.GetAppSetting("SOM_ExportExcelTemplatePath");
            if (templateFilePath.LastIndexOf("\\") != templateFilePath.Length - 1)
                templateFilePath += "\\";
            string templateFile = templateFilePath + string.Format("AdmissionRegistryEnquiry Template.xlsx");//add by jack 20160127 ISU22 fixed for same export file name
            //string exportFile = Server.MapPath("~") + string.Format(@"\Template\MTRC\AdmissionRegistryEnquiry.xlsx");
            string ExcelDownloadFilePath = APJ.Util.Utility.GetAppSetting("SOM_ExportExcelTempFilePath");
            if (ExcelDownloadFilePath.LastIndexOf("\\") != ExcelDownloadFilePath.Length - 1)
                ExcelDownloadFilePath += "\\";
            string exportFile = ExcelDownloadFilePath + string.Format("AdmissionRegistryEnquiry" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");//add by jack 20160127 ISU22 fixed for same export file name
            //update by gordon 20150910
            //CreateExcelFile.ExportExcelWithTemplate(dtSearchResult, templateFile, exportFile, Response);
            CreateExcelFile.ExportExcelWithTemplate(dtSearchResult, templateFile, exportFile, Response, Page);
            /******************* add by dylan 20150727 for u133 end**********************************/

            dtSearchResult.Dispose();
            dtSearchResult = null;
            dsCopyReturn.Dispose();
            dsCopyReturn = null;
            //}
            //else
            //{
            //    return;
            //}
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            this.Response.Redirect(APJ.Util.Utility.GetHttpHost(this.Request) + "/SOM/AdmissionRegistry/AdmissionRegistryEntry.aspx?Action=new");
        }

        protected void grdSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
            {
                ((HyperLink)(e.Row.Cells[0].Controls[0])).Target = "_blank";
                ////huangyao 20081129 in MTR office
                string urlString = APJ.Util.Utility.GetHttpHost(this.Request) + "/SOM/AdmissionRegistry/AdmissionRegistryEntry.aspx?StationEventID=" + grdSearchResult.DataKeys[e.Row.RowIndex]["StationEventID"].ToString().Trim();
                ((HyperLink)(e.Row.Cells[0].Controls[0])).NavigateUrl = "";
                ((HyperLink)(e.Row.Cells[0].Controls[0])).Font.Bold = true;
                string strScript = "OpenEntryPageMaximum('" + urlString + "');";
                ((HyperLink)(e.Row.Cells[0].Controls[0])).Attributes.Add("onclick", strScript);

                //---------------------
                //((TextBox)(e.Row.Cells[5].FindControl("txtFullContent"))).Text = "[Job Nature]" + Environment.NewLine + ((Label)(e.Row.Cells[5].FindControl("lblJobNature"))).Text + Environment.NewLine + Environment.NewLine + "[Job Location]" + Environment.NewLine + ((Label)(e.Row.Cells[5].FindControl("lblJobLocation"))).Text;
                ((TextBox)(e.Row.Cells[5].FindControl("txtFullContent"))).Text = "[" + this.GetLabel("SOM_JobNature", false) + "]" + Environment.NewLine + ((Label)(e.Row.Cells[5].FindControl("lblJobNature"))).Text + Environment.NewLine + Environment.NewLine + "[" + this.GetLabel("SOM_JobLocation", false) + "]" + Environment.NewLine + ((Label)(e.Row.Cells[5].FindControl("lblJobLocation"))).Text;

                ((Button)(e.Row.Cells[5].FindControl("btnShowDetails"))).Attributes.Add("onclick", "javascript:ShowDetails(" + ((TextBox)(e.Row.Cells[5].FindControl("txtFullContent"))).ClientID.ToString() + "); return false;");
                if (((Label)(e.Row.Cells[5].FindControl("lblShortContent"))).Text.Trim().Length >= DetailLength)
                {
                    ((Label)(e.Row.Cells[5].FindControl("lblShortContent"))).Text = ((Label)(e.Row.Cells[5].FindControl("lblShortContent"))).Text.Substring(0, DetailLength);
                }

                if (((Label)e.Row.Cells[6].Controls[1]).Text == "1")
                {
                    ((Image)e.Row.Cells[6].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_OS.gif";
                    //                    ((ImageButton)e.Row.Cells[6].Controls[2]).ToolTip = this.GetLabel("SOM_OS", false);
                    ((Image)e.Row.Cells[6].Controls[2]).ToolTip = ((Label)e.Row.Cells[6].FindControl("lblEventStatusDesc")).Text;
                }
                else if (((Label)e.Row.Cells[6].Controls[1]).Text == "2")
                {
                    ((Image)e.Row.Cells[6].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventStatus_COM.gif";
                    //((ImageButton)e.Row.Cells[6].Controls[2]).ToolTip = this.GetLabel("SOM_Completed", false);
                    ((Image)e.Row.Cells[6].Controls[2]).ToolTip = ((Label)e.Row.Cells[6].FindControl("lblEventStatusDesc")).Text;
                }
                else
                {
                    ((Image)e.Row.Cells[6].Controls[2]).ImageUrl = Request.ApplicationPath.ToString() + "/Images/SOM/EventStatus_Void.gif";
                    //((ImageButton)e.Row.Cells[6].Controls[2]).ToolTip = this.GetLabel("SOM_Void", false);
                    ((Image)e.Row.Cells[6].Controls[2]).ToolTip = ((Label)e.Row.Cells[6].FindControl("lblEventStatusDesc")).Text;
                }

                if (((Label)e.Row.Cells[7].Controls[1]).Text == "True")
                {
                    ((Image)e.Row.Cells[7].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventHandOver.gif";
                    ((Image)e.Row.Cells[7].Controls[2]).ToolTip = grdSearchResult.DataKeys[e.Row.RowIndex]["HandoverNote"].ToString();
                }
                else
                {
                    if (!string.IsNullOrEmpty(grdSearchResult.DataKeys[e.Row.RowIndex]["HandoverNote"].ToString()))
                    {
                        ((Image)e.Row.Cells[7].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/EventHandOverDone.jpg";
                        ((Image)e.Row.Cells[7].Controls[2]).ToolTip = grdSearchResult.DataKeys[e.Row.RowIndex]["HandoverNote"].ToString();
                    }
                    else
                    {
                        ((Image)e.Row.Cells[7].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/spacer.gif";
                    }
                }
                //update by benson 2015.08.27 u183.3 begin
                if (((Label)e.Row.Cells[6].Controls[1]).Text == "2")
                {
                    ((Image)e.Row.Cells[8].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                    ((Image)e.Row.Cells[8].Controls[2]).ToolTip = this.GetLabel("SOM_HighLightNormal", false);
                }
                //update by benson 2015.08.27 u183.3 end
                else
                {
                    if (((Label)e.Row.Cells[8].Controls[1]).Text == "1")
                    {
                        ((Image)e.Row.Cells[8].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Yellow.gif";
                        ((Image)e.Row.Cells[8].Controls[2]).ToolTip = this.GetLabel("SOM_HighLightYellow", false);
                    }
                    else if (((Label)e.Row.Cells[8].Controls[1]).Text == "2")
                    {
                        ((Image)e.Row.Cells[8].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Red.gif";
                        ((Image)e.Row.Cells[8].Controls[2]).ToolTip = this.GetLabel("SOM_HighLightRed", false);
                    }
                    else
                    {
                        ((Image)e.Row.Cells[8].Controls[2]).ImageUrl = Request.ApplicationPath + "/Images/SOM/HighLight_Normal.gif";
                        ((Image)e.Row.Cells[8].Controls[2]).ToolTip = this.GetLabel("SOM_HighLightNormal", false);
                    }
                }
                //e.Row.Cells[4].Text = this.FormatDateTime_AddBR(e.Row.Cells[4].Text);
            }
        }

        #endregion

        #region Method

        /// <summary>
        /// set page element text multi-language
        /// </summary>
        private void SetLanguage()
        {
            this.lblStationLable.Text = this.GetLabel("SOM_Station", true);
            this.lblFlagTimeFrom.Text = this.GetLabel("COM_From", true);
            this.lblFlageTimeTo.Text = this.GetLabel("COM_To", true);
            this.lblFlagDisplay.Text = this.GetLabel("COM_Show", true);
            this.lblFlagWorkCategory.Text = this.GetLabel("SOM_WorkCategory", true);
            this.lblSubCategory.Text = this.GetLabel("SOM_WorkSubCategory", true);
            this.btnSearch.Text = this.GetLabel("COM_Search");
            this.btnOutPut.Text = this.GetLabel("COM_Export");
            this.chkFreeTextSearch.Text = this.GetLabel("COM_FreeTextSearch", true);
            this.rdoAnd.Text = this.GetLabel("SOM_And");
            this.rdoOr.Text = this.GetLabel("SOM_Or");
            this.btnAddNew.Text = this.GetLabel("SOM_AddNewAssetLoanItem");
            BindListControl(cblShow, "EventStatusID", "Description", DAL.SOM.CodeSetup.CDEventStatus.GetActive(this.LangCode), false);
            int intShowCount = this.cblShow.Items.Count;
            for (int i = 0; i < intShowCount; i++)
            {
                if (this.cblShow.Items[i].Value == "1")
                {
                    this.cblShow.Items[i].Selected = true;
                }
            }
            if (intShowCount > 0)
            {
                this.cblShow.Items.Insert(intShowCount - 1, this.GetLabel("SOM_Handover"));
                this.cblShow.Items[intShowCount - 1].Selected = true;
            }
            else
            {
                this.cblShow.Items.Insert(0, this.GetLabel("SOM_Handover"));
                this.cblShow.Items[0].Selected = true;
            }
            BindWorkCategory();
            BindWorkSubCategory();
            this.grdSearchResult.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
        }

        /// <summary>
        /// Custom element initial state of page
        /// </summary>
        private void CustomInitializtion()
        {
            FunctionItemSetting();
            int nDateTime = Convert.ToInt32(CommonData.GetNumVal("SOM_AdmissionRegistry_EnquiryDateRange"));
            // edit by dylan 20150902 for u189 issue log
            this.dtbCreateTimeTo.SetDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime().Date);
            this.dtbCreateTimeFrom.SetDateTime(MTRC.ODMS.DAL.COM.Util.GetCurrentSystemTime().Date.AddDays(-nDateTime));
            btnOutPut.Enabled = false;
            if (DAL.Security.User.CanFunctionItemAccess("M140101_F1", this.ODMUser.UserProfileID, this.MenuID))
            {
                this.btnAddNew.Enabled = false;
            }
            else
            {
                this.btnAddNew.Enabled = true;
            }
            DetailLength = int.Parse(MTRC.ODMS.DAL.CommonData.GetNumVal("SOM_DetailLength").ToString());
        }

        /// <summary>
        /// bind the value with WorkCategory control
        /// </summary>
        private void BindWorkCategory()
        {
            BindListControl(this.ddlWorkCategory, "AdmRegCategoryID", "Description", ODMS.DAL.SOM.CodeSetup.CDAdmRegCategory.GetAllWorkCategory(this.LangCode), true);
            ddlWorkCategory.SelectedIndex = -1;
        }

        /// <summary>
        /// bind the value with WorkSubCategory control
        /// </summary>
        private void BindWorkSubCategory()
        {
            BindListControl(this.ddlSubCategory, "AdmRegSubCategoryID", "Description", ODMS.DAL.SOM.CodeSetup.CDAdmRegSubCategory.GetAllWorkSubCategory(this.LangCode), true);
            ddlSubCategory.SelectedIndex = -1;
        }

        /// <summary>
        /// bind the search result for page
        /// </summary>
        private void BindSearchResult()
        {
            /* Comment by jack 20150822 for u70 */
            if (DAL.Security.User.CanFunctionItemAccess("M140101_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {

            }
            else if (DAL.Security.User.CanFunctionItemAccess("M140101_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {

            }
            else
            {
                if (!IsValidStation(this.ODMUser.LocationID))
                {

                    if (Request.QueryString["IsReject"] != "1")
                    {
                        this.PAlert(this.GetMessage("SOM_NotValidStation"));
                    }
                    this.ddlStation.Items.Clear();
                    DataTable dtNull = new DataTable();
                    this.grdSearchResult.DataSource = dtNull.DefaultView;
                    this.grdSearchResult.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
                    this.grdSearchResult.DataBind();
                    dtNull.Dispose();
                    return;
                }

            }
            /************************************/

            //Check the from date and to date 
            if (dtbCreateTimeFrom.Text.Trim().Length > 0 && dtbCreateTimeTo.Text.Trim().Length > 0)
            {
                if (InvalidateInputDate(this.dtbCreateTimeFrom.GetDateTime(), this.dtbCreateTimeTo.GetDateTime()))
                {
                    PAlert(this.GetMessage("COM_StartEndDate"));
                    return;
                }
            }
            DataTable dtSearchResult = GetSearchResult().Tables[0];
            this.grdSearchResult.GetLabelFunction = new APJ.Web.UI.WebControls.GetLabel(this.GetLabel);
            grdSearchResult.DataSource = dtSearchResult.DefaultView;
            grdSearchResult.DataBind();
        }

        /// <summary>
        /// search DB get data table Collections
        /// </summary>
        /// <returns>get data table of search result</returns>
        private DataSet GetSearchResult()
        {
            bool StatusCom = false;
            bool StatusOS = false;
            bool StatusHandover = false;
            bool StatusVoid = false;
            for (int i = 0; i < this.cblShow.Items.Count; i++)
            {
                if (this.cblShow.Items[i].Selected)
                {
                    if (this.cblShow.Items[i].Value == "2")
                    {
                        StatusCom = true;
                    }
                    else if (this.cblShow.Items[i].Value == "1")
                    {
                        StatusOS = true;
                    }
                    else if (this.cblShow.Items[i].Value == "3")
                    {
                        StatusVoid = true;
                    }
                    else
                    {
                        StatusHandover = true;
                    }
                }
            }
            int intCurrentUsergroup = this.ODMUser.UserGroupID;
            int nIsAnd = -1;
            string strConditionOne = string.Empty;
            string strConditionTwo = string.Empty;
            string strConditionThree = string.Empty;
            if (chkFreeTextSearch.Checked)
            {
                nIsAnd = this.rdoAnd.Checked ? 1 : 0;
                strConditionOne = TxtConditionOne.Text;
                strConditionTwo = TxtConditionTwo.Text;
                strConditionThree = TxtConditionThree.Text;
            }
            string stationIDs = "";
            this.SetStationSelectedItem(ref stationIDs, this.ddlStation);
            DataSet dsEnquiry = MTRC.ODMS.BLL.SOM.Event.StationEventAdmReg.GetAREnquiryFreeTextSearch
                (
                this.LangCode,
                stationIDs,
                this.dtbCreateTimeFrom.GetDateTime(),
                this.dtbCreateTimeTo.GetDateTime(),
                StatusCom,
                StatusOS,
                StatusHandover,
                StatusVoid,
                Convert.ToInt32(ddlWorkCategory.SelectedValue),
                Convert.ToInt32(ddlSubCategory.SelectedValue),
                nIsAnd,
                strConditionOne,
                strConditionTwo,
                strConditionThree
                );

            //edit by hjh 20120516 for issue 1531
            //this.hdnCacheDataReturnInt.Value = BLL.SOM.TempData.CacheDataSet(dsEnquiry, this.ODMUser.ID, this.ODMUser.Domain.ToString()).ToString();
            return dsEnquiry;
        }

        /// <summary>
        /// setting user access by function item.
        /// </summary>
        private void FunctionItemSetting()
        {
            if (DAL.Security.User.CanFunctionItemAccess("M140101_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true);
            }
            else if (DAL.Security.User.CanFunctionItemAccess("M140101_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {
                //BindStation
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), true);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), true);
            }
            else
            {
                //update by gordon 20151020 U247
                //BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID), false);
                BindListControl(this.ddlStation, "LocationID", "station", DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID), false);
                this.ddlStation.Enabled = false;

                /* Comment by jack 20150822 for u70 */
                //if (!IsValidStation(this.ODMUser.LocationID))
                //{
                //    if (Request.QueryString["IsReject"] != "1")
                //    {
                //        this.PAlert(this.GetMessage("SOM_NotValidStation"));
                //    }
                //    this.ddlStation.Items.Clear();
                //}
                /************************************/
            }
            //if (DAL.Security.User.CanFunctionItemAccess("M140101_F3", this.ODMUser.UserProfileID, this.MenuID)) //readonly
            //{
            //    this.btnAddNew.Enabled = false;
            //}
            //update by gordon 20151020 U247
            //if (ddlStation.Items.FindByValue(this.ODMUser.StationID.ToString()) != null)
            if (ddlStation.Items.FindByValue(this.ODMUser.LocationID.ToString()) != null)
            {
                this.ddlStation.SelectedValue = this.CurrentLocation.ToString();
                //this.ddlStation.SelectedIndex = 0;
            }

        }

        #endregion

        #region  added by Nathan 2015-08-15


        /// <summary>
        /// Encryption
        /// </summary>
        public void TxtJM()
        {
            if (TxtConditionOne.Text.Trim().Length > 0)
            {
                string str = TxtConditionOne.Text;

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("AR->TxtConditionOne->Before Encrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                string strJM = APJ.Util.Utility.AESEncrypt(str);

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("AR->TxtConditionOne->After Encrypt:" + strJM, 4, ODMUser.ID, ODMUser.UserGroupName);

                TextOne.Text = strJM;
            }
            else
            {
                TextOne.Text = "";
            }
            if (TxtConditionTwo.Text.Trim().Length > 0)
            {
                string str = TxtConditionTwo.Text;

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("AR->TxtConditionTwo->Before Encrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                string strJM = APJ.Util.Utility.AESEncrypt(str);

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("AR->TxtConditionTwo->After Encrypt:" + strJM, 4, ODMUser.ID, ODMUser.UserGroupName);

                TextTwo.Text = strJM;
            }
            else
            {
                TextTwo.Text = "";
            }
            if (TxtConditionThree.Text.Trim().Length > 0)
            {
                string str = TxtConditionThree.Text;

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("AR->TxtConditionThree->Before Encrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                string strJM = APJ.Util.Utility.AESEncrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("AR->TxtConditionThree->After Encrypt:" + strJM, 4, ODMUser.ID, ODMUser.UserGroupName);

                TextThree.Text = strJM;
            }
            else
            {
                TextThree.Text = "";
            }

        }
        /// <summary>
        /// Decryption
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public void JMText()
        {
            if (TextOne.Text.Trim().Length > 0 && TxtConditionOne.Text.Trim().Length <= 0)
            {
                string str = TextOne.Text;

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("AR->TxtConditionOne->Before Decrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                TxtConditionOne.Text = APJ.Util.Utility.AESDecrypt(str);

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("AR->TxtConditionOne->After Decrypt:" + TxtConditionOne.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

                //TextOne.Text = "";
            }
            if (TextTwo.Text.Trim().Length > 0 && TxtConditionTwo.Text.Trim().Length <= 0)
            {
                string str = TextTwo.Text;

                //add by gordon 20160216 ISU51
               // BLL.SOM.Log.Logger("AR->TxtConditionTwo->Before Decrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                TxtConditionTwo.Text = APJ.Util.Utility.AESDecrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("AR->TxtConditionTwo->After Decrypt:" + TxtConditionTwo.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

                //TextTwo.Text = "";
            }
            if (TextThree.Text.Trim().Length > 0 && TxtConditionThree.Text.Trim().Length <= 0)
            {
                string str = TextThree.Text;

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("AR->TxtConditionThree->Before Decrypt:" + str, 4, ODMUser.ID, ODMUser.UserGroupName);

                TxtConditionThree.Text = APJ.Util.Utility.AESDecrypt(str);

                //add by gordon 20160216 ISU51
                //BLL.SOM.Log.Logger("AR->TxtConditionThree->After Decrypt:" + TxtConditionThree.Text, 4, ODMUser.ID, ODMUser.UserGroupName);

                //TextThree.Text = "";
            }
        }
        protected void chkFreeTextSearch_CheckedChanged(object sender, EventArgs e)
        {
            if (chkFreeTextSearch.Checked)
            {
                TxtConditionOne.Enabled = true;
                TxtConditionTwo.Enabled = true;
                TxtConditionThree.Enabled = true;
                rdoAnd.Enabled = true;
                rdoOr.Enabled = true;

            }
            else
            {
                TxtConditionOne.Enabled = false;
                TxtConditionTwo.Enabled = false;
                TxtConditionThree.Enabled = false;
                rdoAnd.Enabled = false;
                rdoOr.Enabled = false;

                TxtConditionOne.Text = "";
                TxtConditionTwo.Text = "";
                TxtConditionThree.Text = "";
                TextOne.Text = "";
                TextTwo.Text = "";
                TextThree.Text = "";
            }

            if (TextRadio.Text.Trim().Length > 0)
            {
                if (TextRadio.Text.Trim() == "2")
                {
                    rdoAnd.Checked = false;
                    rdoOr.Checked = true;
                }
                else
                {
                    rdoAnd.Checked = true;
                    rdoOr.Checked = false;
                }
            }
        }
        #endregion  added by Nathan 2015-08-15

        /// <summary>
        ///   add by jack 20151202 for using session store enquiry condition
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSetSession_Click(object sender, EventArgs e)
        {
            this.RemoveCommonSession();

            string Url = this.HiddenFieldUrl.Value;
            Session["Common_Station"] = this.ddlStation.SelectedValue.ToString();
            Session["Common_DateFrom"] = this.dtbCreateTimeFrom.Text.ToString();
            Session["Common_DateTo"] = this.dtbCreateTimeTo.Text.ToString();

            string ShowList = this.GetCheckboxListValue(this.cblShow);
            string SubCategory = string.Empty;
            string WorkCategoryValue = this.ddlWorkCategory.SelectedValue.ToString();
            if (WorkCategoryValue == "0")
            {
                SubCategory = "0";
            }
            else
            {
                SubCategory = this.ddlSubCategory.SelectedValue.ToString();
            }
            Session["Common_ShowList"] = ShowList.ToString();
            Session["AR_WorkCategory"] = WorkCategoryValue.ToString();
            Session["AR_SubCategory"] = SubCategory.ToString();
            Session["Common_FreeTextSearch"] = this.chkFreeTextSearch.Checked;
            Session["Common_ConditionOne"] = this.TextOne.Text.ToString();
            Session["Common_ConditionTwo"] = this.TextTwo.Text.ToString();
            Session["Common_ConditionThree"] = this.TextThree.Text.ToString();
            Session["Common_RdoAnd"] = this.rdoAnd.Checked;
            Session["Common_RdoOr"] = this.rdoOr.Checked;
            Response.Redirect(Url + "&isBack=1&PageID=AdmissionRegistryEnquiry");
        }

    }
}
